package pl.us.ij.plugins.segmentation.commands.threshold;

import ij.process.FloatProcessor;
import ij.process.ImageProcessor;
import pl.us.ij.plugins.segmentation.infrastructure.Command;
import pl.us.ij.plugins.segmentation.infrastructure.exceptions.BreakCommandException;

/**
 * Created by IntelliJ IDEA.
 * User: Przemek
 * Date: 2010-01-02
 * Time: 21:13:38
 * To change this template use File | Settings | File Templates.
 */
public class IterativeHistogramThresholdCommand extends Command {
    @Override
    protected void processImage(FloatProcessor fp) throws BreakCommandException {
        ImageProcessor ip = fp;

        float[] pixels = (float[]) ip.getPixels();

        int t = findThreshold(pixels);

        OneLevelThresholdCommand.thresholdPixels(t, pixels, (float)ip.getMin(), (float)ip.getMax());

//        getImageProcessor().setPixels(0, (FloatProcessor) ip);
    }

    public static int findThreshold(float[] pixels) {
        int tp = 0;
        int t = 127;

        while (tp != t) {
            float sumB = 0;
            float sumC = 0;
            int noB = 0;
            int noC = 0;

            for (int i = 0; i < pixels.length; i++) {
                if (pixels[i] > t) {
                    sumB += pixels[i];
                    noB++;
                } else {
                    sumC += pixels[i];
                    noC++;
                }
            }

            tp = t;

            float srB = 0;
            float srC = 0;

            if (noB != 0)
                srB = sumB / noB;

            if (noC != 0) {
                srC = sumC / noC;
            }

            t = Math.round((srB + srC) / 2);
        }
        return t;
    }
}
